import win32gui
import win32con
import ctypes


def find_all_windows_with_title(title_pattern):
    found_windows = []

    def callback(hwnd_temp, extra):
        window_title = win32gui.GetWindowText(hwnd_temp)
        if title_pattern in window_title:
            found_windows.append(hwnd_temp)
        return True

    win32gui.EnumWindows(callback, None)
    if not found_windows:
        print(f"未找到标题包含 '{title_pattern}' 的窗口。")
    return found_windows


def arrange_windows(windows):
    user32 = ctypes.windll.user32
    screen_width = user32.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = user32.GetSystemMetrics(win32con.SM_CYSCREEN)
    window_width = screen_width // 3
    window_height = window_width * 4 // 5
    x, y = 0, 0
    border_width = 7
    index = 1
    for hwnd in windows:
        win32gui.MoveWindow(hwnd, x, y, window_width + border_width, window_height, True)
        # 在窗口标题前加上序号
        # new_title = f"{index}.梦幻西游：时空"
        # win32gui.SetWindowText(hwnd, new_title)
        x += window_width - 7
        index += 1
        if (x+window_width) > screen_width:
            x = 0
            y += window_height + border_width


if __name__ == '__main__':
    title_pattern = "梦幻西游：时空"
    windows = find_all_windows_with_title(title_pattern)
    arrange_windows(windows)
